package com.alfy.sbdemo.websocketdemo.demo2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;

/**
 * WebSocket 配置类
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private MyHandShakeHandler myHandShakeHandler;

    @Resource
    private MyAuthHandshakeInterceptor myAuthHandshakeInterceptor;

    /**
     * 注册 WebSocket 处理器
     *
     * @param registry registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册 WebSocket 处理器和拦截器
        registry.addHandler(webSocketHandler(), "/websocket/server1/{test}")
                .addInterceptors(handshakeInterceptor())
                .setAllowedOrigins("*");
        // 注册 WebSocket 处理器、握手处理程序
        registry.addHandler(webSocketHandler(), "/websocket/server2")
                .setHandshakeHandler(myHandShakeHandler)
                .setAllowedOrigins("*");
        // 注册 WebSocket 处理器和拦截器以及开启 withSockJS +
        registry.addHandler(webSocketHandler(), "/websocket/sockjs")
                 .setAllowedOrigins("*")
                // 开启 sockJs, 记得把 websocketEnabled 也给开启了, 否则客户端只能使用 sockJs, 而不能使用 websocket
                .withSockJS()
                .setWebSocketEnabled(true)
        ;
        // 注册 WebSocket 处理器、握手处理程序
        registry.addHandler(webSocketHandler(), "/websocket/server3")
                .addInterceptors(myAuthHandshakeInterceptor)
                .setAllowedOrigins("*");
    }

    /**
     * WebSocket 处理程序
     *
     * @return {@link WebSocketHandler }
     */
    @Bean
    public WebSocketHandler webSocketHandler() {
        return new MyWebSocketHandler();
    }

    /**
     * WebSocket 拦截器
     *
     * @return {@link HandshakeInterceptor }
     */
    @Bean
    public HandshakeInterceptor handshakeInterceptor() {
        return new MyHandshakeInterceptor();
    }

}
